<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="板材名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="板材名称" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="板材型号" prop="model">
          <el-input v-model="queryParams.model" placeholder="板材型号" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="板材价格（单位：元）" prop="price">
          <el-input v-model="queryParams.price" placeholder="板材价格（单位：元）" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['stone:stone:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button v-hasPerm="['stone:stone:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="ID" prop="id" min-width="150" align="center" />
        <el-table-column key="name" label="板材名称" prop="name" min-width="150" align="center" />
        <el-table-column key="model" label="板材型号" prop="model" min-width="150" align="center" />
        <el-table-column key="image" label="板材图片路径" prop="image" min-width="150" align="center">
          <template #default="scope">
            <!-- <img :src="scope.row.image" /> -->
            <el-image :src="scope.row.image" :preview-src-list="scope.row.image" :preview-teleported="true"
              :style="`width: 40px; height:40px`" />
          </template>
        </el-table-column>
        <el-table-column key="length" label="板材长度（单位：如cm）" prop="length" min-width="150" align="center" />
        <el-table-column key="width" label="板材宽度（单位：如cm）" prop="width" min-width="150" align="center" />
        <el-table-column key="height" label="板材高度（单位：如cm）" prop="height" min-width="150" align="center" />
        <el-table-column key="price" label="板材价格（单位：元）" prop="price" min-width="150" align="center" />
        <el-table-column key="type" label="板材类型（如1：石材；2：木材等）" prop="type" min-width="150" align="center" />
        <el-table-column key="description" label="板材描述" prop="description" min-width="150" align="center" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['stone:stone:edit']" type="primary" size="small" link
              @click="handleOpenDialog(scope.row.id)">
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button v-hasPerm="['stone:stone:delete']" type="danger" size="small" link
              @click="handleDelete(scope.row.id)">
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 板材管理表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" @close="handleCloseDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="180px">
        <el-input v-model="formData.id" type="hidden" />
        <el-form-item label="板材名称" prop="name">
          <el-input v-model="formData.name" placeholder="板材名称" />
        </el-form-item>

        <el-form-item label="板材型号" prop="model">
          <el-input v-model="formData.model" placeholder="板材型号" />
        </el-form-item>

        <el-form-item label="板材图片" prop="image">
          <SingleImageUpload v-model="formData.image" />
          <!-- <el-input v-model="formData.image" placeholder="板材图片" /> -->
        </el-form-item>

        <el-form-item label="板材长度（单位：如cm）" prop="length">
          <el-input-number v-model="formData.length" placeholder="板材长度（单位：如cm）" />
        </el-form-item>

        <el-form-item label="板材宽度（单位：如cm）" prop="width">
          <el-input-number v-model="formData.width" placeholder="板材宽度（单位：如cm）" />
        </el-form-item>

        <el-form-item label="板材高度（单位：如cm）" prop="height">
          <el-input-number v-model="formData.height" placeholder="板材高度（单位：如cm）" />
        </el-form-item>

        <el-form-item label="板材价格（单位：元）" prop="price">
          <el-input v-model="formData.price" placeholder="板材价格（单位：元）" />
        </el-form-item>

        <el-form-item label="板材类型（如1：石材；2：木材等）" prop="type">
          <el-input v-model="formData.type" placeholder="板材类型（如1：石材；2：木材等）" />
        </el-form-item>

        <el-form-item label="板材描述" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="板材描述" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Stone",
  inheritAttrs: false,
});

import StoneAPI, { StonePageVO, StoneForm, StonePageQuery } from "@/api/stone/stone";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<StonePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 板材管理表格数据
const pageData = ref<StonePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 板材管理表单数据
const formData = reactive<StoneForm>({});

// 板材管理表单校验规则
const rules = reactive({
  name: [{ required: true, message: "请输入板材名称", trigger: "blur" }],
});

/** 查询板材管理 */
function handleQuery() {
  loading.value = true;
  StoneAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置板材管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开板材管理弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改板材管理";
    StoneAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增板材管理";
  }
}

/** 提交板材管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        StoneAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        StoneAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭板材管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除板材管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      StoneAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
